package com.yanqu.road.server.manager.activity.witchdraw;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.witchdraw.data.WitchDrawNoticeData;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.logic.bussiness.activity.WitchDrawBusiness;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.WitchDrawProto;
import com.yanqu.road.server.TempCrossMgr;
import com.yanqu.road.server.TempMgr;

import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.ActivityMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class CrossWitchDrawMgr extends TempCrossMgr {

    private static Logger logger = LogManager.getLogger(CrossWitchDrawMgr.class);
    //活动id，公告数据列表
    private static Map<Integer,List<WitchDrawNoticeData>> noticeDataMap = new ConcurrentHashMap<>();
    //需要插入数据库的公告数据列表
    private static List<WitchDrawNoticeData> needInsertNoticeDataList = new ArrayList<>();
    //活动id，活动信息
    private static Map<Integer,ActivityInfo> activityInfoMap = new ConcurrentHashMap<>();
    //活动id,消息体
    private static Map<Integer,List<WitchDrawProto.WitchDrawNoticeData>> noticeMsgMap = new ConcurrentHashMap<>();

    @Override
    public boolean save() {
        if (needInsertNoticeDataList == null){
            return false;
        }
        if (needInsertNoticeDataList.isEmpty()){
            return true;
        }
        List<WitchDrawNoticeData> tmpWitchDrawNoticeDataList = new ArrayList<>(needInsertNoticeDataList);
        needInsertNoticeDataList.clear();
        return WitchDrawBusiness.addWitchDrawNoticeDataList(tmpWitchDrawNoticeDataList);
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        //读出当前正在进行的女巫之夜活动
        Map<Integer, ActivityInfo> tmpActivityMap = ActivityMgr.getOpenCrossActivityMapByType(eActivityType.WitchDraw.getValue());
        activityInfoMap = new ConcurrentHashMap<>(tmpActivityMap);
        List<Integer> activityList = new ArrayList<>();


        for (Map.Entry<Integer, ActivityInfo> entry : activityInfoMap.entrySet()) {
            activityList.add(entry.getKey());
        }
        //读出当前正在进行的女巫之夜活动的公告数据

        for (int activityId : activityList) {
            //先从新到旧 50个 排序
            List<WitchDrawNoticeData> noticeDataList = WitchDrawBusiness.getWitchDrawNoticeData(activityId);
            //反过来
            noticeDataList.sort(Comparator.comparing(WitchDrawNoticeData::getTime));
            //放进去
            noticeDataMap.put(activityId,noticeDataList);
            //重新生成msg
            reGenerateNoticeMsg(activityId);
        }
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    @Override
    public boolean removeExpireData() throws Exception {
        List<Integer> acList = new ArrayList<>();
        long nowTime = System.currentTimeMillis();
        for (ActivityInfo activityInfo: activityInfoMap.values()) {
            if (nowTime > activityInfo.getEndShowTime()  * 1000 + 3 * 24 * 3600 * 1000){
                acList.add(activityInfo.getActivityId());
            }
        }
        for(Integer activityId : acList){
            noticeDataMap.remove(activityId);
            noticeMsgMap.remove(activityId);
            activityInfoMap.remove(activityId);
        }
        return true;
    }

    /**
     * 获取公告数据
     */
    public static WitchDrawProto.WitchDrawGetNoticeDataResp.Builder getActivityNoticeMsg(int activityId){
        WitchDrawProto.WitchDrawGetNoticeDataResp.Builder builder = WitchDrawProto.WitchDrawGetNoticeDataResp.newBuilder();
        if (getActivityInfo(activityId) == null){
            builder.setRet(GameErrorCode.E_WITCH_DRAW_ACTIVITY_NO_OPEN);
            return builder;
        }

        builder.setRet(0);
        if (noticeMsgMap.containsKey(activityId)){
            builder.addAllNoticeData(noticeMsgMap.get(activityId));
        }
        return builder;
    }


    /**
     * 获取活动
     * @param activityId
     * @return
     */

    public static ActivityInfo getActivityInfo(int activityId){
        if (activityInfoMap.containsKey(activityId)){
            return activityInfoMap.get(activityId);
        }
        synchronized (activityInfoMap){
            if (activityInfoMap.containsKey(activityId)){
                return activityInfoMap.get(activityId);
            }
            ActivityInfo activityInfo = ActivityMgr.getActivityInfo(activityId);
            if (activityInfo == null){
                activityInfo = ActivityBussiness.getActivityInfoByActivityId(activityId);
            }
            if (activityInfo != null){
                activityInfoMap.put(activityId,activityInfo);
            }

        }
        return activityInfoMap.get(activityId);
    }

    /**
     * 将消息体转换成公告数据
     * @param noticeData
     * @return
     */
    public static WitchDrawNoticeData parseMsgToNotice(WitchDrawProto.WitchDrawNoticeData noticeData){
        WitchDrawNoticeData witchDrawNoticeData = new WitchDrawNoticeData();
        witchDrawNoticeData.setActivityId(noticeData.getActivityId());
        witchDrawNoticeData.setUserId(noticeData.getUserId());
        witchDrawNoticeData.setServerId(noticeData.getServerId());
        witchDrawNoticeData.setDrawId(noticeData.getDrawId());
        witchDrawNoticeData.setNickName(noticeData.getNickName());
        witchDrawNoticeData.setDrawType(noticeData.getDrawType());
        witchDrawNoticeData.setReward(noticeData.getReward());
        witchDrawNoticeData.setTime(noticeData.getTime());
        return witchDrawNoticeData;
    }

    /**
     * 将公告数据转换成消息体
     * @param noticeData
     * @return
     */
    public static WitchDrawProto.WitchDrawNoticeData parseNoticeToMsg(WitchDrawNoticeData noticeData){
        WitchDrawProto.WitchDrawNoticeData.Builder builder = WitchDrawProto.WitchDrawNoticeData.newBuilder();
        builder.setActivityId(noticeData.getActivityId());
        builder.setUserId(noticeData.getUserId());
        builder.setServerId(noticeData.getServerId());
        builder.setDrawId(noticeData.getDrawId());
        builder.setNickName(noticeData.getNickName());
        builder.setDrawType(noticeData.getDrawType());
        builder.setReward(noticeData.getReward());
        builder.setTime(noticeData.getTime());
        return builder.build();
    }

    /**
     * 上传添加公告数据
     * @param activityId
     * @param noticeData
     * @param userId
     */
    public static void addDrawNotice(int activityId,List<WitchDrawProto.WitchDrawNoticeData> noticeData,long userId){
        ActivityInfo activityInfo = getActivityInfo(activityId);
        if (activityInfo == null){
            logger.error("WitchDrawMgr add DrawNotice error,activityId = {} ,userId = {}",activityId,userId);
            return;
        }
        if (noticeData == null || noticeData.isEmpty()){
            logger.error("WitchDrawMgr add DrawNotice error,noticeData is null,activityId = {} ,userId = {}",activityId,userId);
            return;
        }
        //先加到消息里面
        synchronized (noticeMsgMap){
            if (!noticeMsgMap.containsKey(activityId)){
                noticeMsgMap.putIfAbsent(activityId,new ArrayList<>());
            }
            List<WitchDrawProto.WitchDrawNoticeData> noticeMsgList = noticeMsgMap.get(activityId);
            for (WitchDrawProto.WitchDrawNoticeData msg: noticeData){
                if (noticeMsgList.size() >= 50){
                    noticeMsgList.remove(0);
                }
                noticeMsgList.add(msg);
            }
        }
        //再加到公告数据里面 顺便入库
        synchronized (noticeDataMap){
            if (!noticeDataMap.containsKey(activityId)) {
                noticeDataMap.putIfAbsent(activityId, new ArrayList<>());
            }
            List<WitchDrawNoticeData> noticeDataList = noticeDataMap.get(activityId);
            for (WitchDrawProto.WitchDrawNoticeData msg: noticeData){
                if (noticeDataList.size() >= 50){
                    noticeDataList.remove(0);
                }
                WitchDrawNoticeData witchDrawNoticeData = parseMsgToNotice(msg);
                noticeDataList.add(witchDrawNoticeData);
                needInsertNoticeDataList.add(witchDrawNoticeData);
            }
        }
    }

    /**
     * 重新生成某个活动的公告数据
     */
    public static void reGenerateNoticeMsg(int activityId){
        ActivityInfo activityInfo = getActivityInfo(activityId);
        if (activityInfo == null){
            logger.error("WitchDrawMgr reGenerateNoticeMsg error,activity no found, activityId = {} ",activityId);
            return;
        }
        List<WitchDrawNoticeData> noticeDataList = noticeDataMap.getOrDefault(activityId, new ArrayList<>());
        List<WitchDrawProto.WitchDrawNoticeData> noticeMsgList = new ArrayList<>();
        for (WitchDrawNoticeData data:noticeDataList){
            WitchDrawProto.WitchDrawNoticeData witchDrawNoticeMsgData = parseNoticeToMsg(data);
            noticeMsgList.add(witchDrawNoticeMsgData);
        }
        synchronized (noticeMsgMap){
            noticeMsgMap.put(activityId,noticeMsgList);
        }
    }




}
